﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UYD_WCS.DBUtility;

namespace WCSService
{
    public class Service
    {
        HttpListener httpService = new HttpListener();

        
        public Service(string uri)
        {
            httpService = new HttpListener();
            httpService.Prefixes.Add(uri);
            httpService.Start();
            httpService.BeginGetContext(WCSCallBack, null);


        }

        public void WCSCallBack(IAsyncResult result)
        {
            try
            {
                httpService.BeginGetContext(WCSCallBack, null);
                var context = httpService.EndGetContext(result);
                context.Response.ContentType = "text/plain;charset=UTF-8";
                context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息
                context.Response.ContentEncoding = Encoding.UTF8;
                Response response = new Response { code = "0", message = "成功" };
                if (context.Request.HttpMethod.ToLower() == "post" && context.Request.InputStream != null)
                {
                    StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                    string functoin = context.Request.RawUrl;
                    string receive = reader.ReadToEnd();
                    WriteLog("接收:请求Url[" + context.Request.Url + "]" + receive);
                    try
                    {
                        switch (functoin)
                        {
                            case "/agv/services/agvAddTask"://创建任务
                                response = AgvAddTask(receive);
                                break;
                            case "/agv/services/agvCancelTask"://取消任务
                                response = AgvCancelTask(receive);
                                break;
                            case "/agv/services/agvQueryTaskStatus"://查询任务状态
                                response = AgvQueryTaskStatus(receive);
                                break;
                            case "/agv/services/agvQueryStatus"://查询 AGV 状态
                                response = AgvQueryStatus(receive);
                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        response = new Response { code = "1", message = ex.Message };
                    }
                }
                else
                {
                    response = new Response { code = "1", message = "不支持GET，请用POST方式调用！" };
                }
                string json = JsonConvert.SerializeObject(response);
                WriteLog("回复：" + json);
                var returnByteArr = Encoding.UTF8.GetBytes(json);
                using (var stream = context.Response.OutputStream)
                {
                    //把处理信息返回到客户端
                    stream.Write(returnByteArr, 0, returnByteArr.Length);
                }
            }
            catch (Exception ex) { }
        }

        Response AgvAddTask(string strRequest)
        {
            Response response = new Response { code = "0", message = "成功" };
            try
            {
                string err = string.Empty;
                ForWCS.AgvAddTask_Request request = JsonConvert.DeserializeObject<ForWCS.AgvAddTask_Request>(strRequest);
                if (request == null)
                {
                    response.code = "1";
                    response.message = "请求参数错误，解析失败";
                }
                else
                {
                    //
                    //将任务增加到本地数据库中
                    string sql = " SELECT COUNT(taskCode) FROM  WCS_AGV_TASK WHERE taskCode='" + request.taskCode+ "' AND reqCode='"+request.reqCode+"' ";
                    if (DbHelperSQLite.RecordCount(sql)>0)
                    {
                        response.reqCode = request.reqCode;
                        response.code = "1";
                        response.message = "任务单号重复";
                    }
                    else
                    {
                        /// <summary>
                        /// WCS发送的起始取货对应的排
                        /// </summary>
                        int startLocGroup = 0;
                        /// <summary>
                        /// WCS发送的起始取货对应的列
                        /// </summary>
                        int startLocColl = 0;
                        /// <summary>
                        /// WCS发送的起始取货对应的层
                        /// </summary>
                        int startLocFloor = 0;


                        /// <summary>
                        /// WCS发送的起始放货对应的排
                        /// </summary>
                        int endLocGroup = 0;
                        /// <summary>
                        /// WCS发送的起始放货对应的列
                        /// </summary>
                        int endLocColl = 0;
                        /// <summary>
                        /// WCS发送的起始放货对应的层
                        /// </summary>
                        int endLocFloor = 0;

                        string startAgvLoc = "";
                        string endAgvLoc = "";
                        bool blExist = false;
                        sql = " SELECT * FROM WCS_AGV_LOC WHERE WCS_LOC='" + request.startPosition + "';  ";
                        DataSet dsAgvLoc = DbHelperSQLite.Query(sql);
                        if(dsAgvLoc!=null)
                            if(dsAgvLoc.Tables.Count>0)
                                if(dsAgvLoc.Tables[0].Rows.Count>0)
                                {
                                    startLocGroup = int.Parse(dsAgvLoc.Tables[0].Rows[0]["LOC_GROUP"].ToString());
                                    startLocColl = int.Parse(dsAgvLoc.Tables[0].Rows[0]["LOC_COLL"].ToString());
                                    startLocFloor = int.Parse(dsAgvLoc.Tables[0].Rows[0]["LOC_FLOOR"].ToString());
                                    startAgvLoc = dsAgvLoc.Tables[0].Rows[0]["AGV_LOC"].ToString();
                                    blExist = true;
                                }
                        if (!blExist)
                        {
                            response.reqCode = request.reqCode;
                            response.code = "1";
                            response.message = "起始储位对应的AGV储位不存在!";
                        }
                        else
                        {
                            blExist = false;
                            sql = " SELECT * FROM WCS_AGV_LOC WHERE WCS_LOC='" + request.endPosition + "';  ";
                            DataSet dsAgvLocEnd = DbHelperSQLite.Query(sql);
                            if (dsAgvLocEnd != null)
                                if (dsAgvLocEnd.Tables.Count > 0)
                                    if (dsAgvLocEnd.Tables[0].Rows.Count > 0)
                                    {
                                        endLocGroup = int.Parse(dsAgvLocEnd.Tables[0].Rows[0]["LOC_GROUP"].ToString());
                                        endLocColl = int.Parse(dsAgvLocEnd.Tables[0].Rows[0]["LOC_COLL"].ToString());
                                        endLocFloor = int.Parse(dsAgvLocEnd.Tables[0].Rows[0]["LOC_FLOOR"].ToString());
                                        endAgvLoc = dsAgvLocEnd.Tables[0].Rows[0]["AGV_LOC"].ToString();
                                        blExist = true;
                                    }
                            if (!blExist)
                            {
                                response.reqCode = request.reqCode;
                                response.code = "1";
                                response.message = "终止储位对应的AGV储位不存在!";
                            }
                            else
                            {
                                sql = "INSERT INTO WCS_AGV_TASK (taskCode,reqCode,reqTime,startPosition,endPosition,"+
                                    "priority,taskStatus,startLocGroup,startLocColl,startLocFloor," +
                                    "endLocGroup,endLocColl,endLocFloor,startAgvLoc,endAgvLoc)" +
                                    "VALUES" +
                                    "('"+ request.taskCode + "','"+ request.reqCode + "','"+ request.reqTime + "','"+ request.startPosition + "','"+ request.endPosition + "'," +
                                    "'"+ request.priority + "','-10','"+startLocGroup+"','"+startLocColl+"','"+startLocFloor+"'," +
                                    "'"+endLocGroup+"','"+endLocColl+"','"+endLocFloor+"','"+startAgvLoc+"','"+endAgvLoc+"');";
                                
                                
                                DbHelperSQLite.ExecuteSql(sql);

                                response.reqCode = request.reqCode;
                                response.code = "0";
                                response.message = "任务添加成功";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response.code = "1";
                response.message = ex.Message;
            }
            return response;
        }
        
        Response AgvCancelTask(string strRequest)
        {
            Response response = new Response { code = "0", message = "成功" };
            try
            {
                string err = string.Empty;
                ForWCS.AgvCancelTask_Request request = JsonConvert.DeserializeObject<ForWCS.AgvCancelTask_Request>(strRequest);
                if (request == null)
                {
                    response.code = "1";
                    response.message = "请求参数错误，解析失败";
                }
                else
                {

                    string sql = " UPDATE WCS_AGV_TASK SET taskStatus='100' WHERE taskCode='" + request.taskCode + "'";
                    DbHelperSQLite.ExecuteSql(sql);
                    response.reqCode = request.reqCode;
                    response.code = "0";
                    response.message = "任务取消成功";
                }
            }
            catch (Exception ex)
            {
                response.code = "1";
                response.message = ex.Message;
            }
            return response;
        }

        Response AgvQueryTaskStatus(string strRequest)
        {
            Response response = new Response { code = "0", message = "成功" };
            try
            {
                string err = string.Empty;
                ForWCS.AgvQueryTaskStatus_Request request = JsonConvert.DeserializeObject<ForWCS.AgvQueryTaskStatus_Request>(strRequest);
                if (request == null)
                {
                    response.code = "1";
                    response.message = "请求参数错误，解析失败";
                }
                else
                {
                    List<ForWCS.TaskStatus> list = new List<ForWCS.TaskStatus>();
                    foreach (string taskCode in request.taskCodes)
                    {
                        //
                        //查询AGV任务状态
                        //
                        ForWCS.TaskStatus status = new ForWCS.TaskStatus { taskCode = taskCode, taskStatus = "2" };
                        list.Add(status);
                    }
                    response.data = list;
                    response.reqCode = request.reqCode;
                }
            }
            catch (Exception ex)
            {
                response.code = "1";
                response.message = ex.Message;
            }
            return response;
        }

        string[] agvCodes = "1|2".Split('|');
        Response AgvQueryStatus(string strRequest)
        {
            Response response = new Response { code = "0", message = "成功" };
            try
            {
                string err = string.Empty;
                ForWCS.AgvQueryStatus_Request request = JsonConvert.DeserializeObject<ForWCS.AgvQueryStatus_Request>(strRequest);
                if (request == null)
                {
                    response.code = "1";
                    response.message = "请求参数错误，解析失败";
                }
                else
                {
                    List<ForWCS.AgvStuatus> list = new List<ForWCS.AgvStuatus>();
                    foreach (string agvCode in agvCodes)
                    {
                        //if (currentAgvStatus.charging)
                        //{ }
                        //查询AGV状态
                        //
                        ForWCS.AgvStuatus status = new ForWCS.AgvStuatus { robotCode = agvCode, status = "4" };
                        list.Add(status);
                    }
                    response.reqCode = request.reqCode;
                }
            }
            catch (Exception ex)
            {
                response.code = "1";
                response.message = ex.Message;
            }
            return response;
        }

        private static object _logLocker = new object();
        private static string _logPath = AppDomain.CurrentDomain.BaseDirectory + @"AGV_WCS_Logs\";
        public static void WriteLog(string msg)
        {
            lock (_logLocker)
            {
                try
                {
                    msg = "[" + DateTime.Now.ToString("HH:mm:ss.fff") + "]" + msg + Environment.NewLine;
                    if (!Directory.Exists(_logPath))
                        Directory.CreateDirectory(_logPath);
                    File.AppendAllText(_logPath + DateTime.Now.ToString("yyyy-MM-dd") + ".log", msg);
                }
                catch { }
            }
        }
    }
}
